package com.mall.shopping.services;

import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZhangXiao on 2021/7/21
 */
@Service
public class ICartServiceImpl implements ICartService {
//    Config config = new Config();
//    //配置config对象
//    SingleServerConfig serverConfig = config.useSingleServer().setAddress("redis://localhost:6379");
//    //创建redis客户端
//    RedissonClient redissonClient = Redisson.create(config);

    //这样写上面三步就可以不用
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;


    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        List<CartProductDto> cartProductDtos = new ArrayList<>();

        try {
            Long userId = request.getUserId();
//            RedissonClient redissonClient = RedissionUtil.creat();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");

            //如果当前用户未进行过购物车相关操作
            if (!addCart.containsKey(userId)) {
                cartListByIdResponse.setCartProductDtos(cartProductDtos);
                cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
                cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                return cartListByIdResponse;
            } else {
                List<AddCartBO> addCartBOS = addCart.get(userId);
                for (AddCartBO addCartBO : addCartBOS) {
                    Long productId = addCartBO.getProductId();
                    Integer productNum = addCartBO.getProductNum();
                    Item item = itemMapper.selectByPrimaryKey(productId);
                    CartProductDto cartProductDto = CartItemConverter.item2Dto(item);
                    int temp = productNum;
                    cartProductDto.setProductNum(Long.valueOf(temp));
                    cartProductDto.setChecked(addCartBO.getChecked());
                    cartProductDtos.add(cartProductDto);
                }

                cartListByIdResponse.setCartProductDtos(cartProductDtos);
                cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
                cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                return cartListByIdResponse;
            }
        } catch (Exception e) {
            cartListByIdResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return cartListByIdResponse;
    }

    @Override
    public AddCartResponse addToCart(AddCartRequest request) {

        AddCartResponse addCartResponse = new AddCartResponse();

        //添加商品，通过key值判断添加的商品是否已存在
        try {
            request.requestCheck();
//            RedissonClient redissonClient = RedissionUtil.creat();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");


            AddCartBO addCartBO = new AddCartBO();
            addCartBO.setProductId(request.getProductId());
            addCartBO.setUserId(request.getUserId());
            addCartBO.setProductNum(request.getProductNum());
            addCartBO.setChecked("true");

            //判断redis中是否已经存在当前用户的记录
            if (addCart.containsKey(request.getUserId())) {
                //若存在，只需要找到对应的商品，去修改商品数量
                List<AddCartBO> addCartBOS = addCart.get(request.getUserId());
                int temp = 0;//添加标记
                for (AddCartBO cartBO : addCartBOS) {
                    //若商品已存在，则只用增加商品数量
                    if (cartBO.getProductId().equals(request.getProductId())) {
                        Integer productNum = cartBO.getProductNum();
                        productNum = productNum + request.getProductNum();
                        cartBO.setProductNum(productNum);
                        temp++;
                    }
                }
                if (temp == 0) {
                    addCartBOS.add(0, addCartBO);
                }
                addCart.put(request.getUserId(), addCartBOS);
            } else {
                List<AddCartBO> addCartBOS = new ArrayList<>();
                addCartBOS.add(0, addCartBO);
                addCart.put(request.getUserId(), addCartBOS);
            }
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return addCartResponse;

        } catch (Exception e) {
            addCartResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return addCartResponse;
    }


    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse updateCartNumResponse = new UpdateCartNumResponse();

        try {
            request.getChecked();
//            RedissonClient redissonClient = RedissionUtil.creat();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");
            List<AddCartBO> addCartBOS = addCart.get(request.getUserId());
            for (AddCartBO addCartBO : addCartBOS) {
                if (addCartBO.getProductId().equals(request.getProductId())) {
                    addCartBO.setChecked(request.getChecked());
                    addCartBO.setProductNum(request.getProductNum());
                }
            }
            addCart.put(request.getUserId(), addCartBOS);
            updateCartNumResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return updateCartNumResponse;
        } catch (Exception e) {
            updateCartNumResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            updateCartNumResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return updateCartNumResponse;


    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse checkAllItemResponse = new CheckAllItemResponse();

        try {
            request.requestCheck();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");
            List<AddCartBO> addCartBOS = addCart.get(request.getUserId());

            for (AddCartBO addCartBO : addCartBOS) {
                addCartBO.setChecked("true");
            }

            addCart.put(request.getUserId(), addCartBOS);

            checkAllItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            checkAllItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return checkAllItemResponse;
        } catch (Exception e) {
            checkAllItemResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            checkAllItemResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }

        return checkAllItemResponse;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();

        try {
            request.requestCheck();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");
            List<AddCartBO> addCartBOS = addCart.get(request.getUserId());

            ArrayList<AddCartBO> toRemove = new ArrayList<>();
            for (AddCartBO addCartBO : addCartBOS) {
                if (addCartBO.getProductId().equals(request.getItemId())) {
                    // 删除addBO
                    toRemove.add(addCartBO);
                }
            }

            addCartBOS.removeAll(toRemove);
            addCart.put(request.getUserId(), addCartBOS);

            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return deleteCartItemResponse;
        } catch (Exception e) {
            deleteCartItemResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return deleteCartItemResponse;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne deleteCheckedItemResposne = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");
            List<AddCartBO> addCartBOS = addCart.get(request.getUserId());
            System.out.println("addCartBOS" + addCartBOS.toArray().toString());

            ArrayList<AddCartBO> toRemove = new ArrayList<>();
            for (AddCartBO addCartBO : addCartBOS) {
                if ("true".equals(addCartBO.getChecked())) {
                    toRemove.add(addCartBO);
                }
            }

            System.out.println("addCartBOS" + toRemove.toArray().toString());
            addCartBOS.removeAll(toRemove);
            addCart.put(request.getUserId(), addCartBOS);

            deleteCheckedItemResposne.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return deleteCheckedItemResposne;
        } catch (Exception e) {
            deleteCheckedItemResposne.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            deleteCheckedItemResposne.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
        }
        return deleteCheckedItemResposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse response = new ClearCartItemResponse();

        try {
            request.requestCheck();
            RMap<Long, List<AddCartBO>> addCart = redissonClient.getMap("AddCart");
            List<AddCartBO> addCartBOS = addCart.get(request.getUserId());
            List<Long> productToDeleteIds = request.getProductIds();

            for (Long productToDeleteId : productToDeleteIds) {
                addCartBOS.removeIf(addCartBO -> addCartBO.getProductId().equals(productToDeleteId));
            }

            addCart.put(request.getUserId(), addCartBOS);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
            e.printStackTrace();
        }
        return response;
    }
}
